/*
 * $Id: ft_sender.c,v 1.5 2005/04/12 06:27:39 woodzy Exp $
 */

#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <strings.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h> 
#include <netdb.h>
#include <netinet/in.h>

#include "nwsim.h"
#include "ft_arq.h"

int ft_debug;
int ft_speed=0;

int main(int argc,char *argv[])
{
  FILE* fileptr;
  char* filename;
  
  int	sockfd;
  struct sockaddr_in	sAddr, simAddr;
  struct hostent *host;

  struct ft_arq_t arq_dev;

  if (strcmp("-d",argv[1]) == 0)
  {
    ft_debug = 1;
    filename = argv[2];
  }
  else
  {
    ft_debug = 0;
    filename = argv[1];
  }

  if (NULL == (fileptr = fopen(filename,"r")))
  {
    printf("%s: invalid filename or permission denied.\n",argv[0]);
    perror("");
    _exit(1);
  } 

  if (NULL == (host = gethostbyname(NWSIM_LOSSY_HOST))) 
  {
    printf("%s: can't resolve name %s\n",argv[0],NWSIM_HOST);
    _exit(1);
  }

  bzero(&simAddr, sizeof(simAddr));
  simAddr.sin_family = AF_INET;
  simAddr.sin_addr.s_addr = *((u_long *)host->h_addr);
  simAddr.sin_port = htons(NWSIM_PORT);

  bzero(&sAddr, sizeof(sAddr));
  sAddr.sin_family = AF_INET;
  sAddr.sin_addr.s_addr = htonl(INADDR_ANY);
  sAddr.sin_port = htons(SENDER_PORT);

  if  ((sockfd = socket(AF_INET,SOCK_DGRAM,0)) < 0 ) 
  {
    printf("%s: cannot open udp socket on port %d (already in use?)\n",argv[0],SENDER_PORT);
    _exit(0);
  }

  if (bind(sockfd,(struct sockaddr*)&sAddr, sizeof(sAddr)) != 0) 
  {
    perror("Failure: can't bind to socket port. ");
    close(sockfd);
    _exit(0);
  }
  if (connect(sockfd,(struct sockaddr*)&simAddr,sizeof(simAddr)) < 0)
  {
    perror("Failure: could not pretend to \"connect\" to the simulator.\n");
    close(sockfd);
    _exit(0);
  }

  ft_arq_setup(&arq_dev,sockfd);
  if (ft_arq_send_file(&arq_dev,fileptr) < 0)
  {
    printf("%s: file send failed -- peer may have gone down.\n",argv[0]);
    _exit(0);
  }
  close(sockfd);
  fclose(fileptr);
  return 0;
}
